<template>
    <BackgroundImage>
        <TopNavigation title="创建房间" backText="房间列表" :titleSub='"赛程:" + scheduleName' />

        <view class="match-create-container">
            <BoxView :titBoxObj="{
                title: '创建房间',
                titleCount: `填写赛事基本信息`
            }" style="width: 70%;background-color: #FFFFF4;">
                <view class="match-create-form">
                    <view class="form-item">
                        <text class="form-label">房间名称 <text class="form-label-required">*</text></text>
                        <input class="form-input" v-model="formData.name" placeholder="请输入房间名称" maxlength="100" />
                    </view>
                    <view class="form-item">
                        <text class="form-label">房主 <text class="form-label-required">*</text></text>
                        <input class="form-input" v-model="formData.owner" placeholder="请输入房主ID" maxlength="100" />
                    </view>
                    <view class="form-item">
                        <text class="form-label">比赛时间 <text class="form-label-required">*</text></text>
                        <view class="form-input">
                            <picker mode="date" :value="matchDate" @change="onDateChange">
                                <text v-if="matchDate">{{ matchDate }}</text>
                                <text v-else style="color: #969696;">请选择比赛时间</text>
                            </picker>
                        </view>
                    </view>

                    <view class="form-item">
                        <text class="form-label">获胜模式</text>
                        <view class="form-input">
                            <picker class="form-picker" mode="selector" :range="winModelOptions" :value="winModelIndex"
                                @change="onWinModelChange">
                                <text class="picker-text">{{ winModelOptions[winModelIndex] }}</text>
                            </picker>
                        </view>
                    </view>
                    <view class="form-item">
                        <text class="form-label">开始类型</text>
                        <view class="form-input">
                            <picker class="form-picker" mode="selector" :range="startTypeOptions"
                                :value="startTypeIndex" @change="onStartTypeChange">
                                <text class="picker-text">{{ startTypeOptions[startTypeIndex] }}</text>
                            </picker>
                        </view>
                    </view>
                </view>
                <view class="match-create-button">
                    <view class="submit-btn" @click="updateRoom" :disabled="loading">
                        {{ submitting ? '更新中...' : '更新房间' }}
                    </view>
                    <view class="cancel-btn" @click="goBack">取消</view>
                </view>
            </BoxView>
        </view>

    </BackgroundImage>
</template>

<script setup>
import BoxView from "@/components/UiView/BoxView.vue";
import TopNavigation from "@/components/UiView/TopNavigation.vue";
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchRoomAPI } from '@/api/battle.js'
import BackgroundImage from "@/components/BackgroundImage.vue";

const scheduleId = ref('')
const scheduleName = ref('')
const roomId = ref('')
const loading = ref(false)
const submitting = ref(false)

const formData = ref({
  name: '',
  owner: '',
  matchTime: Date.now(),
  status: 1,
  winModel: 1,
  startType: 1
})

const matchDate = ref('')
const statusIndex = ref(0)
const winModelIndex = ref(0)
const startTypeIndex = ref(0)

const statusOptions = [
  '等待',
  '准备',
  '倒计时',
  '开始比赛',
  '结束比赛',
  '暂停',
  '取消/终止',
  '异常'
]

const winModelOptions = [
  '一回合 抢1分',
  '三回合 抢2分',
  '五回合 抢3分',
  '高分',
  'BO3',
  'AO5',
  'BAO5',
  '时间短',
  '步数短',
  '距离长',
  '五局（抢3） 五回合（抢3）'
]

const startTypeOptions = [
  '定时开赛',
  '手动开赛',
  '人满即开'
]

const fetchRoomData = async () => {
  if (!roomId.value) return
  
  loading.value = true
  try {
    const result = await MatchRoomAPI.page({
      matchRoomId: roomId.value,
      pageNum: 0,
      pageSize: 1
    })
    
    if (result.code === 0 && result.data?.length > 0) {
      const room = result.data[0]
      formData.value = {
        name: room.name || '',
        owner: room.owner || '',
        matchTime: room.matchTime || Date.now(),
        status: room.status || 1,
        winModel: room.winModel || 1,
        startType: room.startType || 1
      }
      
      statusIndex.value = (room.status || 1) - 1
      winModelIndex.value = (room.winModel || 1) - 1
      startTypeIndex.value = room.startType || 1
      
      if (room.matchTime) {
        const date = new Date(room.matchTime)
        matchDate.value = date.toISOString().split('T')[0]
      }
    }
  } catch (error) {
    console.error('获取房间数据失败:', error)
    uni.showToast({
      title: '获取房间数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onLoad((options) => {
  if (options.roomId) {
    roomId.value = options.roomId
  }
  if (options.scheduleId) {
    scheduleId.value = options.scheduleId
  }
  if (options.scheduleName) {
    scheduleName.value = decodeURIComponent(options.scheduleName || '')
  }
  
  fetchRoomData()
})

const onDateChange = (e) => {
  matchDate.value = e.detail.value
  const date = new Date(e.detail.value)
  formData.value.matchTime = date.getTime()
}

const onStatusChange = (e) => {
  statusIndex.value = e.detail.value
  formData.value.status = parseInt(e.detail.value) + 1
}

const onWinModelChange = (e) => {
  winModelIndex.value = e.detail.value
  formData.value.winModel = parseInt(e.detail.value) + 1
}

const onStartTypeChange = (e) => {
  startTypeIndex.value = e.detail.value
  formData.value.startType = parseInt(e.detail.value)
}

const updateRoom = async () => {
  if (!formData.value.name.trim()) {
    uni.showToast({
      title: '请输入房间名称',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const result = await MatchRoomAPI.edit({
      matchRoomId: roomId.value,
      matchScheduleId: scheduleId.value,
      name: formData.value.name,
      owner: formData.value.owner,
      matchTime: formData.value.matchTime,
      status: formData.value.status,
      winModel: formData.value.winModel,
      startType: formData.value.startType
    })
    
    if (result.code === 0) {
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
      setTimeout(() => {
        goBack()
      }, 1500)
    } else {
      throw new Error(result.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新房间失败:', error)
    uni.showToast({
      title: error.message || '更新失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.match-create-button {
  display: flex;
  justify-content: center;
  align-items: center;
  // margin-top: 5rpx;

  view {
    height: 30rpx;
    width: 118rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14rpx;
  }

  .submit-btn {
    color: #FFFFFF;
    background: url('/static/buttons/button6.png') no-repeat center center;
    background-size: 100% 100%;
  }

  .cancel-btn {
    background: url('/static/buttons/button7.png') no-repeat center center;
    background-size: 100% 100%;
    color: #000000;
  }
}


.match-create-form {
  background-color: #F0F0E4;
  overflow: auto;
  border-radius: 10rpx;
  margin: 10rpx;
  margin-bottom: 5rpx;
  padding: 10rpx;
  height: calc(100% - 100rpx);

  .form-item {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10rpx;

    .form-label {
      font-size: 14rpx;
      width: 80rpx;
      text-align: right;
      color: #333;

      .form-label-required {
        color: orangered;
      }
    }

    .form-input {
      margin-left: 10rpx;
      height: 26rpx;
      line-height: 26rpx;
      padding: 0 10rpx;
      font-size: 13rpx;
      color: #000000;
      background-color: #DADADA;
      border-radius: 4rpx;
      width: 130rpx;
    }
  }
}

.match-create-container {
  height: calc(100vh - 55rpx);
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-bottom: 20rpx;
}
</style>